<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆座位预约系统 - 预约查询</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f0f8ff;
            min-height: 100vh;
            color: #333;
            display: flex;
            flex-direction: column;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            flex: 1;
        }
        .current-booking-card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }

        /* 头部样式 */
        .main-header {
            background-color: rgba(255, 255, 255, 0.95);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px 0;
        }

        .header-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.5rem;
            font-weight: bold;
            color: #1a2a6c;
        }

        .main-nav ul {
            display: flex;
            list-style: none;
            gap: 20px;
        }

        .main-nav a {
            text-decoration: none;
            color: #333;
            padding: 8px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .main-nav a:hover, .main-nav li.active a {
            background-color: #1a73e8;
            color: white;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .welcome {
            font-weight: 500;
        }

        /* 主要内容区域 */
        .main-content {
            flex: 1;
            padding: 20px 0;
        }

        .management-header {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
        }

        .management-header h1 {
            color: #1a2a6c;
            margin-bottom: 20px;
            font-size: 2rem;
        }

        /* 当前预约信息 */
        .current-booking {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
        }

        .current-booking h2 {
            color: #1a2a6c;
            margin-bottom: 20px;
            font-size: 1.5rem;
        }

        .booking-card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .booking-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .info-item {
            display: flex;
            flex-direction: column;
        }

        .info-label {
            font-weight: 500;
            color: #1a2a6c;
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 1.1rem;
        }

        .status-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-badge.pending {
            background-color: #ffc107;
            color: #212529;
        }

        .status-badge.fulfilled {
            background-color: #28a745;
            color: white;
        }

        .status-badge.temporary-leave {
            background-color: #17a2b8;
            color: white;
        }

        .status-badge.expired {
            background-color: #6c757d;
            color: white;
        }

        .status-badge.available {
            background-color: #50c878;
            color: white;
        }

        .status-badge.completed {
            background-color: #28a745;
            color: white;
        }

        .status-badge.canceled {
            background-color: #6c757d;
            color: white;
        }

        .status-badge.breach {
            background-color: #dc3545;
            color: white;
        }

        .booking-actions {
            display: flex;
            gap: 15px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            font-size: 0.9rem;
        }

        .btn-primary {
            background: #1a73e8;
            color: white;
        }

        .btn-primary:hover:not(:disabled) {
            background: #0d62d9;
        }

        .btn-secondary {
            background: #f1f3f4;
            color: #333;
        }

        .btn-secondary:hover {
            background: #e0e0e0;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .no-booking {
            text-align: center;
            padding: 40px 20px;
            color: #7f8c8d;
        }

        .no-booking p {
            margin-bottom: 20px;
            font-size: 1.1rem;
        }

        .time-info {
            background-color: #e9ecef;
            border-radius: 5px;
            padding: 10px 15px;
            margin-bottom: 15px;
            font-size: 0.9rem;
        }

        .time-info.warning {
            background-color: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffc107;
        }

        .time-info.expired {
            background-color: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .countdown {
            font-weight: bold;
            color: #dc3545;
            font-size: 1.1rem;
        }

        /* 历史预约记录 */
        .history-bookings {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .history-header h2 {
            color: #1a2a6c;
            font-size: 1.5rem;
        }

        .filter-controls {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .filter-group label {
            font-weight: 500;
            color: #1a2a6c;
        }

        .filter-group select, .filter-group input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 0.9rem;
        }

        .booking-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .booking-table th {
            background-color: #f8f9fa;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
            color: #1a2a6c;
            border-bottom: 2px solid #dee2e6;
        }

        .booking-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #dee2e6;
        }

        .booking-table tr:hover {
            background-color: #f8f9fa;
        }

        /* 调整表格列宽，删除两列后重新分配 */
        .booking-table th:nth-child(1),
        .booking-table td:nth-child(1) {
            width: 25%;
        }

        .booking-table th:nth-child(2),
        .booking-table td:nth-child(2) {
            width: 15%;
        }

        .booking-table th:nth-child(3),
        .booking-table td:nth-child(3) {
            width: 35%;
        }

        .booking-table th:nth-child(4),
        .booking-table td:nth-child(4) {
            width: 25%;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header-container {
                flex-direction: column;
                gap: 15px;
            }

            .main-nav ul {
                flex-wrap: wrap;
                justify-content: center;
            }

            .user-info {
                flex-direction: column;
                gap: 10px;
            }

            .filter-controls {
                flex-direction: column;
                gap: 10px;
            }

            .booking-info {
                grid-template-columns: 1fr;
            }

            .booking-actions {
                flex-direction: column;
            }

            .booking-table {
                display: block;
                overflow-x: auto;
            }

            .booking-table th,
            .booking-table td {
                padding: 8px 10px;
                font-size: 0.85rem;
            }
        }
    </style>
</head>
<body>
<header class="main-header">
    <div class="header-container">
        <div class="logo">
            <span>图书馆座位预约系统</span>
        </div>
        <nav class="main-nav">
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="seat-selection.html">座位选择</a></li>
                <li class="active"><a href="booking-management.html">预约查询</a></li>
                <li><a href="user-profile.html">个人中心</a></li>
            </ul>
        </nav>
        <div class="user-info">
            <span class="welcome" id = "welcome">欢迎，张三同学</span>
        </div>
    </div>
</header>

<main class="main-content">
    <div class="container">
        <section class="management-header">
            <h1>预约查询</h1>
        </section>

        <!-- 当前预约信息 -->
        <section class="current-booking">
            <h2>当前预约信息</h2>
            <div id="current-booking-container">
                <!-- 多个当前预约将在此处动态生成 -->
                <div id="current-bookings-list"></div>

                <!-- 无当前预约时显示 -->
                <div class="no-booking" id="no-booking-message" style="display: none;">
                    <p>暂无当前预约</p>
                    <a href="seat-selection.html" class="btn btn-primary">立即预约</a>
                </div>
            </div>
        </section>

        <!-- 历史预约记录 -->
        <section class="history-bookings">
            <div class="history-header">
                <h2>历史预约记录</h2>
                <div class="filter-controls">
                    <div class="filter-group">
                        <label for="status-filter">预约状态：</label>
                        <select id="status-filter">
                            <option value="all">全部</option>
                            <option value="completed">已履约</option>
                            <option value="pending">待履约</option>
                            <option value="canceled">已取消</option>
                            <option value="breach">违约</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label for="date-filter">时间范围：</label>
                        <input type="date" id="date-filter" max="">
                    </div>
                </div>
            </div>
            <div class="list-container">
                <table class="booking-table">
                    <thead>
                    <tr>
                        <th>座位区域</th>
                        <th>座位号</th>
                        <th>预约时间</th>
                        <th>预约状态</th>
                    </tr>
                    </thead>
                    <tbody id="history-booking-list">
                    <!-- 历史预约记录将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </section>
    </div>
</main>

<script>
    // 1. 常量定义
    const BASE_URL = 'http://localhost:8080/api';

    // 2. 全局变量
    let currentBookings = [];
    let historyBookings = [];
    let countdownTimer = null;

    // 3. DOM 元素引用
    let currentBookingCard, noBookingMessage, checkInBtn, temporaryLeaveBtn, cancelBookingBtn;
    let statusFilter, dateFilter, historyBookingList, timeInfo, checkInDeadline;

    // 4. 工具函数
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 楼层映射函数 - 根据座位ID判断楼层
    function mapSeatIdToFloorName(seatId) {
        const seatNum = parseInt(seatId);

        if (seatNum >= 1 && seatNum <= 400) {
            return '1楼-阅览区';
        } else if (seatNum >= 401 && seatNum <= 800) {
            return '2楼-电子阅览区';
        } else if (seatNum >= 801 && seatNum <= 1400) {
            return '3楼-考公考研区';
        } else if (seatNum >= 1401 && seatNum <= 1408) {
            return '4楼-阅读区';
        } else if (seatNum >= 1409 && seatNum <= 1708) {
            return '5楼-讨论区';
        } else {
            return `楼层未知 (座位ID: ${seatId})`;
        }
    }

    // 5. 用户相关函数
    async function loadUserInfo(username) {
        try {
            const res = await fetch(`${BASE_URL}/user/get-info?username=${username}`);
            if (!res.ok) throw new Error('网络异常');
            const student = await res.json();
            document.getElementById('welcome').textContent = `欢迎，${student.username} 同学`;
        } catch (e) {
            console.error(e);
            alert('加载用户信息失败');
        }
    }

    // 6. API 调用函数
    async function fetchUserReservations() {
        try {
            const username = sessionStorage.getItem('currentUser');
            const response = await fetch(`${BASE_URL}/seat/reservations?days=7`, {
                headers: {
                    'username': username
                }
            });

            if (!response.ok) throw new Error('获取预约记录失败');
            const reservations = await response.json();
            console.log('预约记录:', reservations);
            return reservations;
        } catch (error) {
            console.error('获取预约记录失败:', error);
            return [];
        }
    }

    // 7. 数据处理函数 - 更新状态映射以匹配后端Reservation模型
    function mapBackendStatusToFrontend(backendStatus) {
        const statusMap = {
            'pending_fulfillment': 'pending',
            'fulfilled': 'fulfilled',
            'cancelled': 'canceled',
            'breach': 'breach'
        };
        return statusMap[backendStatus] || 'pending';
    }

    function processReservations(reservations) {
        const now = new Date();
        const today = now.toISOString().split('T')[0];

        let currentBookings = [];
        const historyBookings = [];

        reservations.forEach(reservation => {

            const reservationDate = new Date(reservation.date).toISOString().split('T')[0];
            const isToday = reservationDate === today;

            // 只处理未履约的预约（待履约、已履约）
            const isActive = reservation.status === 'pending_fulfillment' ||
                reservation.status === 'fulfilled';

            // 使用新的楼层映射函数，根据座位ID判断楼层
            const floorName = mapSeatIdToFloorName(reservation.seatId);

            const bookingData = {
                id: reservation.id,
                floorName: floorName,
                seatId: reservation.seatId,
                date: reservation.dateText,
                startTime: reservation.startTime,
                endTime: reservation.endTime,
                status: mapBackendStatusToFrontend(reservation.status),
                canCancel: reservation.canCancel,
                canCheckIn: reservation.canCheckIn,
                backendStatus: reservation.status, // 保存后端状态用于逻辑判断
                seatStatus: reservation.seatStatus
            };

            if (isToday && isActive) {
                currentBookings.push(bookingData);
            } else {
                historyBookings.push(bookingData);
            }
        });

        return { currentBookings, historyBookings };
    }

    // 8. 时间计算函数
    function calculateCheckInTimeRange(bookingStartTime, bookingEndTime) {
        const now = new Date();
        const startHour = parseInt(bookingStartTime.split(':')[0]);
        const endHour = parseInt(bookingEndTime.split(':')[0]);

        const bookingStart = new Date();
        bookingStart.setHours(startHour, 0, 0, 0);

        const bookingEnd = new Date();
        bookingEnd.setHours(endHour, 0, 0, 0);

        let checkInStart, checkInEnd;

        if (now >= bookingStart && now <= bookingEnd) {
            checkInStart = new Date(now);
            checkInEnd = new Date(now.getTime() + 30 * 60 * 1000);
        } else {
            checkInStart = new Date(bookingStart.getTime() - 30 * 60 * 1000);
            checkInEnd = new Date(bookingStart.getTime() + 30 * 60 * 1000);
        }

        return {
            start: checkInStart,
            end: checkInEnd
        };
    }

    // 9. UI 更新函数
    function updateCurrentBookingDisplay() {
        const currentBookingsList = document.getElementById('current-bookings-list');
        const noBookingMessage = document.getElementById('no-booking-message');

        if (currentBookings.length > 0) {
            currentBookingsList.innerHTML = '';
            noBookingMessage.style.display = 'none';

            currentBookings.forEach(booking => {
                const bookingCard = document.createElement('div');
                bookingCard.className = 'current-booking-card';
                bookingCard.id = `booking-${booking.id}`;

                // 根据状态确定按钮状态和显示文本
                const { checkInBtnText, checkInBtnDisabled, leaveBtnText, leaveBtnDisabled, cancelBtnDisabled, timeInfo } = getBookingDisplayConfig(booking);

                bookingCard.innerHTML = `
                <div class="time-info ${timeInfo.class}" id="time-info-${booking.id}">
                    ${timeInfo.text}
                </div>
                <div class="booking-info">
                    <div class="info-item">
                        <span class="info-label">预约区域</span>
                        <span class="info-value">${booking.floorName}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">座位号</span>
                        <span class="info-value">${booking.seatId}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">预约时间段</span>
                        <span class="info-value">${booking.date} ${booking.startTime}-${booking.endTime}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">座位状态</span>
                        <span class="info-value">
                            <span class="status-badge ${booking.status}" id="current-status-${booking.id}">${getStatusText(booking.status)}</span>
                        </span>
                    </div>
                </div>
                <div class="booking-actions">
                    <button class="btn btn-primary check-in-btn" data-id="${booking.id}" ${checkInBtnDisabled ? 'disabled' : ''}>${checkInBtnText}</button>
                    <button class="btn btn-secondary temporary-leave-btn" data-id="${booking.id}" ${leaveBtnDisabled ? 'disabled' : ''}>${leaveBtnText}</button>
                    <button class="btn btn-danger cancel-booking-btn" data-id="${booking.id}" ${cancelBtnDisabled ? 'disabled' : ''}>退座</button>
                </div>
            `;

                currentBookingsList.appendChild(bookingCard);
            });

            // 重新绑定事件监听器
            bindCurrentBookingEvents();

        } else {
            currentBookingsList.innerHTML = '';
            noBookingMessage.style.display = 'block';
        }
    }

    // 获取预约显示配置
    function getBookingDisplayConfig(booking) {
        console.log("状态" + booking.seatStatus);
        const config = {
            checkInBtnText: '落座',
            checkInBtnDisabled: false,
            leaveBtnText: '暂离',
            leaveBtnDisabled: true,
            cancelBtnDisabled: false,
            timeInfo: { class: '', text: '' }
        };

        switch(booking.backendStatus) {
            case 'pending_fulfillment':
                config.checkInBtnText = '落座';
                config.checkInBtnDisabled = false;
                config.leaveBtnText = '暂离';
                config.leaveBtnDisabled = true;
                config.timeInfo = {
                    class: 'warning',
                    text: '请在规定时间内完成落座，否则将自动释放座位'
                };
                break;

            case 'fulfilled':
                config.checkInBtnText = '已落座';
                config.checkInBtnDisabled = true;

                // 根据seatStatus判断按钮文本
                if (booking.seatStatus === 'AWAY') {
                    config.leaveBtnText = '返回';
                    config.timeInfo = {
                        class: 'warning',
                        text: '请在90分钟内返回并落座，否则将自动释放座位并记违约'
                    };
                } else {
                    config.leaveBtnText = '暂离';
                    config.timeInfo = {
                        class: '',
                        text: '座位使用中，可点击"暂离"暂时离开座位'
                    };
                }
                config.leaveBtnDisabled = false;
                break;
        }

        return config;
    }

    // 辅助函数：获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'pending': '待履约',
            'fulfilled': '已履约',
            'temporary-leave': '暂离中',
            'expired': '已过期',
            'completed': '已履约',
            'canceled': '已取消',
            'breach': '违约'
        };
        return statusMap[status] || '待履约';
    }

    function updateHistoryBookingsDisplay() {
        historyBookingList.innerHTML = '';

        if (historyBookings.length === 0) {
            const row = document.createElement('tr');
            row.innerHTML = `
            <td colspan="4" style="text-align: center; color: #7f8c8d; padding: 40px;">
                暂无历史预约记录
            </td>
        `;
            historyBookingList.appendChild(row);
            return;
        }

        historyBookings.forEach(booking => {
            const row = document.createElement('tr');
            row.className = 'booking-row';

            let statusClass = '';
            let statusText = '';

            switch(booking.status) {
                case 'completed':
                    statusClass = 'completed';
                    statusText = '已履约';
                    break;
                case 'canceled':
                    statusClass = 'canceled';
                    statusText = '已取消';
                    break;
                case 'breach':
                    statusClass = 'breach';
                    statusText = '违约';
                    break;
                case 'fulfilled':
                    statusClass = 'fulfilled';
                    statusText = '已履约';
                    break;
                case 'temporary-leave':
                    statusClass = 'temporary-leave';
                    statusText = '暂离中';
                    break;
                default:
                    statusClass = 'pending';
                    statusText = '待履约';
            }

            row.innerHTML = `
            <td>${booking.floorName}</td>
            <td>${booking.seatId}</td>
            <td>${booking.date} ${booking.startTime}-${booking.endTime}</td>
            <td><span class="status-badge ${statusClass}">${statusText}</span></td>
        `;
            historyBookingList.appendChild(row);
        });
    }

    // 10. 业务逻辑函数
    async function loadReservationData() {
        try {
            const reservations = await fetchUserReservations();
            const processed = processReservations(reservations);

            currentBookings = processed.currentBookings;
            historyBookings = processed.historyBookings;

            updateCurrentBookingDisplay();
            updateHistoryBookingsDisplay();

        } catch (error) {
            console.error('加载预约数据失败:', error);
            alert('加载预约数据失败');
        }
    }

    function setMaxDateForFilter() {
        const today = new Date();
        const todayStr = formatDate(today);
        dateFilter.max = todayStr;
    }

    function filterHistoryBookings() {
        const status = statusFilter.value;
        const date = dateFilter.value;

        const rows = historyBookingList.querySelectorAll('.booking-row');

        rows.forEach(row => {
            let showRow = true;

            if (status !== 'all') {
                const rowStatus = row.querySelector('.status-badge').textContent;
                const statusMap = {
                    'completed': '已履约',
                    'pending': '待履约',
                    'canceled': '已取消',
                    'breach': '违约'
                };

                if (statusMap[status] !== rowStatus) {
                    showRow = false;
                }
            }

            if (date) {
                const rowDate = row.cells[2].textContent.split(' ')[0];
                if (rowDate !== date) {
                    showRow = false;
                }
            }

            row.style.display = showRow ? '' : 'none';
        });
    }

    // 11. 新增暂离和返回功能
    async function temporaryLeave(e) {
        const bookingId = e.target.dataset.id;
        const booking = currentBookings.find(b => b.id == bookingId);
        if (!booking) return;

        try {
            const username = sessionStorage.getItem('currentUser');
            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/away`, {
                method: 'POST',
                headers: {
                    'username': username,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(errorText);
            }

            // 关键修改：暂离成功后立即更新按钮状态，无需等待重新加载数据
            e.target.textContent = '返回';
            // 更新提示信息
            const timeInfoElement = document.getElementById(`time-info-${bookingId}`);
            if (timeInfoElement) {
                timeInfoElement.className = 'time-info warning';
                timeInfoElement.textContent = '请在90分钟内返回并落座，否则将自动释放座位并记违约';
            }

            alert('暂离成功！请在90分钟内返回');

        } catch (error) {
            console.error('暂离失败:', error);
            alert('暂离失败: ' + error.message);
        }
    }

    async function returnFromLeave(e) {
        const bookingId = e.target.dataset.id;
        const booking = currentBookings.find(b => b.id == bookingId);
        if (!booking) return;

        try {
            const username = sessionStorage.getItem('currentUser');
            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/return`, {
                method: 'POST',
                headers: {
                    'username': username,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(errorText);
            }

            // 关键修改：返回成功后立即更新按钮状态，无需等待重新加载数据
            e.target.textContent = '暂离';
            // 更新提示信息
            const timeInfoElement = document.getElementById(`time-info-${bookingId}`);
            if (timeInfoElement) {
                timeInfoElement.className = 'time-info';
                timeInfoElement.textContent = '座位使用中，可点击"暂离"暂时离开座位';
            }

            alert('返回成功！');

        } catch (error) {
            console.error('返回失败:', error);
            alert('返回失败: ' + error.message);
        }
    }

    // 12. 事件处理函数
    async function handleCheckIn(e) {
        const bookingId = e.target.dataset.id;
        const booking = currentBookings.find(b => b.id == bookingId);
        if (!booking) return;

        try {
            const username = sessionStorage.getItem('currentUser');
            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/checkin`, {
                method: 'POST',
                headers: {
                    'username': username,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(errorText);
            }

            alert('签到成功！');
            await loadReservationData();

        } catch (error) {
            console.error('签到失败:', error);
            alert('签到失败: ' + error.message);
        }
    }

    async function handleTemporaryLeave(e) {
        const bookingId = e.target.dataset.id;
        const booking = currentBookings.find(b => b.id == bookingId);
        if (!booking) return;

        // 根据按钮文本判断当前操作
        if (e.target.textContent === '暂离') {
            // 执行暂离操作
            await temporaryLeave(e);
        } else if (e.target.textContent === '返回') {
            // 执行返回操作
            await returnFromLeave(e);
        }
    }

    async function handleCancelBooking(e) {
        const bookingId = e.target.dataset.id;
        const booking = currentBookings.find(b => b.id == bookingId);
        if (!booking) return;

        if (!confirm('确定要退座吗？')) return;

        try {
            const username = sessionStorage.getItem('currentUser');
            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/cancel`, {
                method: 'POST',
                headers: {
                    'username': username,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(errorText);
            }

            alert('退座成功！');
            await loadReservationData();

        } catch (error) {
            console.error('退座失败:', error);
            alert('退座失败: ' + error.message);
        }
    }

    // 13. 初始化函数
    function initializeElements() {
        statusFilter = document.getElementById('status-filter');
        dateFilter = document.getElementById('date-filter');
        historyBookingList = document.getElementById('history-booking-list');
    }

    function bindEventListeners() {
        // 为筛选控件添加事件监听
        if (statusFilter) {
            statusFilter.addEventListener('change', filterHistoryBookings);
        }
        if (dateFilter) {
            dateFilter.addEventListener('change', filterHistoryBookings);
        }
    }

    // 绑定当前预约卡片的事件
    function bindCurrentBookingEvents() {
        const currentBookingsList = document.getElementById('current-bookings-list');
        if (currentBookingsList) {
            currentBookingsList.addEventListener('click', function(e) {
                if (e.target.classList.contains('check-in-btn')) {
                    handleCheckIn(e);
                } else if (e.target.classList.contains('temporary-leave-btn')) {
                    handleTemporaryLeave(e);
                } else if (e.target.classList.contains('cancel-booking-btn')) {
                    handleCancelBooking(e);
                }
            });
        }
    }

    async function initialize() {
        const user = sessionStorage.getItem('currentUser');
        if (!user) {
            alert('请先登录');
            location.href = 'login.html';
            return;
        }

        await loadUserInfo(user);
        initializeElements();
        bindEventListeners();
        setMaxDateForFilter();
        await loadReservationData();
    }

    // 14. 程序入口
    document.addEventListener('DOMContentLoaded', initialize);
</script>
</body>
</html>


<!--<!DOCTYPE html>-->
<!--<html lang="zh-CN">-->
<!--<head>-->
<!--    <meta charset="UTF-8">-->
<!--    <meta name="viewport" content="width=device-width, initial-scale=1.0">-->
<!--    <title>图书馆座位预约系统 - 预约查询</title>-->
<!--    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">-->
<!--    <style>-->
<!--        * {-->
<!--            margin: 0;-->
<!--            padding: 0;-->
<!--            box-sizing: border-box;-->
<!--            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;-->
<!--        }-->

<!--        body {-->
<!--            background-color: #f0f8ff;-->
<!--            min-height: 100vh;-->
<!--            color: #333;-->
<!--            display: flex;-->
<!--            flex-direction: column;-->
<!--        }-->

<!--        .container {-->
<!--            max-width: 1200px;-->
<!--            margin: 0 auto;-->
<!--            padding: 20px;-->
<!--            flex: 1;-->
<!--        }-->
<!--        .current-booking-card {-->
<!--            background-color: #f8f9fa;-->
<!--            border-radius: 8px;-->
<!--            padding: 20px;-->
<!--            margin-bottom: 20px;-->
<!--            border: 1px solid #e9ecef;-->
<!--        }-->

<!--        /* 头部样式 */-->
<!--        .main-header {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);-->
<!--            padding: 15px 0;-->
<!--        }-->

<!--        .header-container {-->
<!--            max-width: 1200px;-->
<!--            margin: 0 auto;-->
<!--            padding: 0 20px;-->
<!--            display: flex;-->
<!--            justify-content: space-between;-->
<!--            align-items: center;-->
<!--        }-->

<!--        .logo {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 10px;-->
<!--            font-size: 1.5rem;-->
<!--            font-weight: bold;-->
<!--            color: #1a2a6c;-->
<!--        }-->

<!--        .main-nav ul {-->
<!--            display: flex;-->
<!--            list-style: none;-->
<!--            gap: 20px;-->
<!--        }-->

<!--        .main-nav a {-->
<!--            text-decoration: none;-->
<!--            color: #333;-->
<!--            padding: 8px 15px;-->
<!--            border-radius: 5px;-->
<!--            transition: background-color 0.3s;-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 5px;-->
<!--        }-->

<!--        .main-nav a:hover, .main-nav li.active a {-->
<!--            background-color: #1a73e8;-->
<!--            color: white;-->
<!--        }-->

<!--        .user-info {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 15px;-->
<!--        }-->

<!--        .welcome {-->
<!--            font-weight: 500;-->
<!--        }-->

<!--        /* 主要内容区域 */-->
<!--        .main-content {-->
<!--            flex: 1;-->
<!--            padding: 20px 0;-->
<!--        }-->

<!--        .management-header {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 25px;-->
<!--            margin-bottom: 30px;-->
<!--        }-->

<!--        .management-header h1 {-->
<!--            color: #1a2a6c;-->
<!--            margin-bottom: 20px;-->
<!--            font-size: 2rem;-->
<!--        }-->

<!--        /* 当前预约信息 */-->
<!--        .current-booking {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 25px;-->
<!--            margin-bottom: 30px;-->
<!--        }-->

<!--        .current-booking h2 {-->
<!--            color: #1a2a6c;-->
<!--            margin-bottom: 20px;-->
<!--            font-size: 1.5rem;-->
<!--        }-->

<!--        .booking-card {-->
<!--            background-color: #f8f9fa;-->
<!--            border-radius: 8px;-->
<!--            padding: 20px;-->
<!--            margin-bottom: 20px;-->
<!--        }-->

<!--        .booking-info {-->
<!--            display: grid;-->
<!--            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));-->
<!--            gap: 15px;-->
<!--            margin-bottom: 20px;-->
<!--        }-->

<!--        .info-item {-->
<!--            display: flex;-->
<!--            flex-direction: column;-->
<!--        }-->

<!--        .info-label {-->
<!--            font-weight: 500;-->
<!--            color: #1a2a6c;-->
<!--            margin-bottom: 5px;-->
<!--        }-->

<!--        .info-value {-->
<!--            font-size: 1.1rem;-->
<!--        }-->

<!--        .status-badge {-->
<!--            display: inline-block;-->
<!--            padding: 5px 10px;-->
<!--            border-radius: 20px;-->
<!--            font-size: 0.85rem;-->
<!--            font-weight: 500;-->
<!--        }-->

<!--        .status-badge.pending {-->
<!--            background-color: #ffc107;-->
<!--            color: #212529;-->
<!--        }-->

<!--        .status-badge.fulfilled {-->
<!--            background-color: #28a745;-->
<!--            color: white;-->
<!--        }-->

<!--        .status-badge.temporary-leave {-->
<!--            background-color: #17a2b8;-->
<!--            color: white;-->
<!--        }-->

<!--        .status-badge.expired {-->
<!--            background-color: #6c757d;-->
<!--            color: white;-->
<!--        }-->

<!--        .status-badge.available {-->
<!--            background-color: #50c878;-->
<!--            color: white;-->
<!--        }-->

<!--        .status-badge.completed {-->
<!--            background-color: #28a745;-->
<!--            color: white;-->
<!--        }-->

<!--        .status-badge.canceled {-->
<!--            background-color: #6c757d;-->
<!--            color: white;-->
<!--        }-->

<!--        .status-badge.breach {-->
<!--            background-color: #dc3545;-->
<!--            color: white;-->
<!--        }-->

<!--        .booking-actions {-->
<!--            display: flex;-->
<!--            gap: 15px;-->
<!--        }-->

<!--        .btn {-->
<!--            padding: 10px 20px;-->
<!--            border: none;-->
<!--            border-radius: 5px;-->
<!--            cursor: pointer;-->
<!--            font-weight: 500;-->
<!--            transition: all 0.3s;-->
<!--            font-size: 0.9rem;-->
<!--        }-->

<!--        .btn-primary {-->
<!--            background: #1a73e8;-->
<!--            color: white;-->
<!--        }-->

<!--        .btn-primary:hover:not(:disabled) {-->
<!--            background: #0d62d9;-->
<!--        }-->

<!--        .btn-secondary {-->
<!--            background: #f1f3f4;-->
<!--            color: #333;-->
<!--        }-->

<!--        .btn-secondary:hover {-->
<!--            background: #e0e0e0;-->
<!--        }-->

<!--        .btn-danger {-->
<!--            background: #dc3545;-->
<!--            color: white;-->
<!--        }-->

<!--        .btn-danger:hover {-->
<!--            background: #c82333;-->
<!--        }-->

<!--        .btn:disabled {-->
<!--            opacity: 0.6;-->
<!--            cursor: not-allowed;-->
<!--        }-->

<!--        .no-booking {-->
<!--            text-align: center;-->
<!--            padding: 40px 20px;-->
<!--            color: #7f8c8d;-->
<!--        }-->

<!--        .no-booking p {-->
<!--            margin-bottom: 20px;-->
<!--            font-size: 1.1rem;-->
<!--        }-->

<!--        .time-info {-->
<!--            background-color: #e9ecef;-->
<!--            border-radius: 5px;-->
<!--            padding: 10px 15px;-->
<!--            margin-bottom: 15px;-->
<!--            font-size: 0.9rem;-->
<!--        }-->

<!--        .time-info.warning {-->
<!--            background-color: #fff3cd;-->
<!--            color: #856404;-->
<!--            border-left: 4px solid #ffc107;-->
<!--        }-->

<!--        .time-info.expired {-->
<!--            background-color: #f8d7da;-->
<!--            color: #721c24;-->
<!--            border-left: 4px solid #dc3545;-->
<!--        }-->

<!--        .countdown {-->
<!--            font-weight: bold;-->
<!--            color: #dc3545;-->
<!--            font-size: 1.1rem;-->
<!--        }-->

<!--        /* 历史预约记录 */-->
<!--        .history-bookings {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 25px;-->
<!--        }-->

<!--        .history-header {-->
<!--            display: flex;-->
<!--            justify-content: space-between;-->
<!--            align-items: center;-->
<!--            margin-bottom: 20px;-->
<!--        }-->

<!--        .history-header h2 {-->
<!--            color: #1a2a6c;-->
<!--            font-size: 1.5rem;-->
<!--        }-->

<!--        .filter-controls {-->
<!--            display: flex;-->
<!--            gap: 20px;-->
<!--            flex-wrap: wrap;-->
<!--        }-->

<!--        .filter-group {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 10px;-->
<!--        }-->

<!--        .filter-group label {-->
<!--            font-weight: 500;-->
<!--            color: #1a2a6c;-->
<!--        }-->

<!--        .filter-group select, .filter-group input {-->
<!--            padding: 8px 12px;-->
<!--            border: 1px solid #ddd;-->
<!--            border-radius: 5px;-->
<!--            font-size: 0.9rem;-->
<!--        }-->

<!--        .booking-table {-->
<!--            width: 100%;-->
<!--            border-collapse: collapse;-->
<!--            margin-top: 20px;-->
<!--        }-->

<!--        .booking-table th {-->
<!--            background-color: #f8f9fa;-->
<!--            padding: 12px 15px;-->
<!--            text-align: left;-->
<!--            font-weight: 600;-->
<!--            color: #1a2a6c;-->
<!--            border-bottom: 2px solid #dee2e6;-->
<!--        }-->

<!--        .booking-table td {-->
<!--            padding: 12px 15px;-->
<!--            border-bottom: 1px solid #dee2e6;-->
<!--        }-->

<!--        .booking-table tr:hover {-->
<!--            background-color: #f8f9fa;-->
<!--        }-->

<!--        /* 调整表格列宽，删除两列后重新分配 */-->
<!--        .booking-table th:nth-child(1),-->
<!--        .booking-table td:nth-child(1) {-->
<!--            width: 25%;-->
<!--        }-->

<!--        .booking-table th:nth-child(2),-->
<!--        .booking-table td:nth-child(2) {-->
<!--            width: 15%;-->
<!--        }-->

<!--        .booking-table th:nth-child(3),-->
<!--        .booking-table td:nth-child(3) {-->
<!--            width: 35%;-->
<!--        }-->

<!--        .booking-table th:nth-child(4),-->
<!--        .booking-table td:nth-child(4) {-->
<!--            width: 25%;-->
<!--        }-->

<!--        /* 响应式设计 */-->
<!--        @media (max-width: 768px) {-->
<!--            .header-container {-->
<!--                flex-direction: column;-->
<!--                gap: 15px;-->
<!--            }-->

<!--            .main-nav ul {-->
<!--                flex-wrap: wrap;-->
<!--                justify-content: center;-->
<!--            }-->

<!--            .user-info {-->
<!--                flex-direction: column;-->
<!--                gap: 10px;-->
<!--            }-->

<!--            .filter-controls {-->
<!--                flex-direction: column;-->
<!--                gap: 10px;-->
<!--            }-->

<!--            .booking-info {-->
<!--                grid-template-columns: 1fr;-->
<!--            }-->

<!--            .booking-actions {-->
<!--                flex-direction: column;-->
<!--            }-->

<!--            .booking-table {-->
<!--                display: block;-->
<!--                overflow-x: auto;-->
<!--            }-->

<!--            .booking-table th,-->
<!--            .booking-table td {-->
<!--                padding: 8px 10px;-->
<!--                font-size: 0.85rem;-->
<!--            }-->
<!--        }-->
<!--    </style>-->
<!--</head>-->
<!--<body>-->
<!--<header class="main-header">-->
<!--    <div class="header-container">-->
<!--        <div class="logo">-->
<!--            <span>图书馆座位预约系统</span>-->
<!--        </div>-->
<!--        <nav class="main-nav">-->
<!--            <ul>-->
<!--                <li><a href="index.html">首页</a></li>-->
<!--                <li><a href="seat-selection.html">座位选择</a></li>-->
<!--                <li class="active"><a href="booking-management.html">预约查询</a></li>-->
<!--                <li><a href="user-profile.html">个人中心</a></li>-->
<!--            </ul>-->
<!--        </nav>-->
<!--        <div class="user-info">-->
<!--            <span class="welcome" id = "welcome">欢迎，张三同学</span>-->
<!--        </div>-->
<!--    </div>-->
<!--</header>-->

<!--<main class="main-content">-->
<!--    <div class="container">-->
<!--        <section class="management-header">-->
<!--            <h1>预约查询</h1>-->
<!--        </section>-->

<!--        &lt;!&ndash; 当前预约信息 &ndash;&gt;-->
<!--        <section class="current-booking">-->
<!--            <h2>当前预约信息</h2>-->
<!--            <div id="current-booking-container">-->
<!--                &lt;!&ndash; 多个当前预约将在此处动态生成 &ndash;&gt;-->
<!--                <div id="current-bookings-list"></div>-->

<!--                &lt;!&ndash; 无当前预约时显示 &ndash;&gt;-->
<!--                <div class="no-booking" id="no-booking-message" style="display: none;">-->
<!--                    <p>暂无当前预约</p>-->
<!--                    <a href="seat-selection.html" class="btn btn-primary">立即预约</a>-->
<!--                </div>-->
<!--            </div>-->
<!--        </section>-->

<!--        &lt;!&ndash; 历史预约记录 &ndash;&gt;-->
<!--        <section class="history-bookings">-->
<!--            <div class="history-header">-->
<!--                <h2>历史预约记录</h2>-->
<!--                <div class="filter-controls">-->
<!--                    <div class="filter-group">-->
<!--                        <label for="status-filter">预约状态：</label>-->
<!--                        <select id="status-filter">-->
<!--                            <option value="all">全部</option>-->
<!--                            <option value="completed">已履约</option>-->
<!--                            <option value="pending">待履约</option>-->
<!--                            <option value="canceled">已取消</option>-->
<!--                            <option value="breach">违约</option>-->
<!--                        </select>-->
<!--                    </div>-->
<!--                    <div class="filter-group">-->
<!--                        <label for="date-filter">时间范围：</label>-->
<!--                        <input type="date" id="date-filter" max="">-->
<!--                    </div>-->
<!--                </div>-->
<!--            </div>-->
<!--            <div class="list-container">-->
<!--                <table class="booking-table">-->
<!--                    <thead>-->
<!--                    <tr>-->
<!--                        <th>座位区域</th>-->
<!--                        <th>座位号</th>-->
<!--                        <th>预约时间</th>-->
<!--                        <th>预约状态</th>-->
<!--                    </tr>-->
<!--                    </thead>-->
<!--                    <tbody id="history-booking-list">-->
<!--                    &lt;!&ndash; 历史预约记录将通过JavaScript动态生成 &ndash;&gt;-->
<!--                    </tbody>-->
<!--                </table>-->
<!--            </div>-->
<!--        </section>-->
<!--    </div>-->
<!--</main>-->

<!--<script>-->
<!--    // 1. 常量定义-->
<!--    const BASE_URL = 'http://localhost:8080/api';-->

<!--    // 2. 全局变量-->
<!--    let currentBookings = [];-->
<!--    let historyBookings = [];-->
<!--    let countdownTimer = null;-->

<!--    // 3. DOM 元素引用-->
<!--    let currentBookingCard, noBookingMessage, checkInBtn, temporaryLeaveBtn, cancelBookingBtn;-->
<!--    let statusFilter, dateFilter, historyBookingList, timeInfo, checkInDeadline;-->

<!--    // 4. 工具函数-->
<!--    function formatDate(date) {-->
<!--        const year = date.getFullYear();-->
<!--        const month = String(date.getMonth() + 1).padStart(2, '0');-->
<!--        const day = String(date.getDate()).padStart(2, '0');-->
<!--        return `${year}-${month}-${day}`;-->
<!--    }-->

<!--    // 5. 用户相关函数-->
<!--    async function loadUserInfo(username) {-->
<!--        try {-->
<!--            const res = await fetch(`${BASE_URL}/user/get-info?username=${username}`);-->
<!--            if (!res.ok) throw new Error('网络异常');-->
<!--            const student = await res.json();-->
<!--            document.getElementById('welcome').textContent = `欢迎，${student.username} 同学`;-->
<!--        } catch (e) {-->
<!--            console.error(e);-->
<!--            alert('加载用户信息失败');-->
<!--        }-->
<!--    }-->

<!--    // 6. API 调用函数-->
<!--    async function fetchUserReservations() {-->
<!--        try {-->
<!--            const username = sessionStorage.getItem('currentUser');-->
<!--            const response = await fetch(`${BASE_URL}/seat/reservations?days=7`, {-->
<!--                headers: {-->
<!--                    'username': username-->
<!--                }-->
<!--            });-->

<!--            if (!response.ok) throw new Error('获取预约记录失败');-->
<!--            const reservations = await response.json();-->
<!--            return reservations;-->
<!--        } catch (error) {-->
<!--            console.error('获取预约记录失败:', error);-->
<!--            return [];-->
<!--        }-->
<!--    }-->

<!--    // 7. 数据处理函数 - 更新状态映射以匹配后端Reservation模型-->
<!--    function mapBackendStatusToFrontend(backendStatus) {-->
<!--        const statusMap = {-->
<!--            'pending_fulfillment': 'pending',-->
<!--            'fulfilled': 'fulfilled',-->
<!--            'cancelled': 'canceled',-->
<!--            'breach': 'breach'-->
<!--        };-->
<!--        return statusMap[backendStatus] || 'pending';-->
<!--    }-->

<!--    function processReservations(reservations) {-->
<!--        const now = new Date();-->
<!--        const today = now.toISOString().split('T')[0];-->

<!--        let currentBookings = [];-->
<!--        const historyBookings = [];-->

<!--        reservations.forEach(reservation => {-->
<!--            const reservationDate = new Date(reservation.date).toISOString().split('T')[0];-->
<!--            const isToday = reservationDate === today;-->

<!--            // 只处理未履约的预约（待履约、已履约）-->
<!--            const isActive = reservation.status === 'pending_fulfillment' ||-->
<!--                reservation.status === 'fulfilled';-->

<!--            const bookingData = {-->
<!--                id: reservation.id,-->
<!--                floorName: `楼层 ${reservation.floorAreaId || '未知'}`,-->
<!--                seatId: reservation.seatId,-->
<!--                date: reservation.dateText,-->
<!--                startTime: reservation.startTime,-->
<!--                endTime: reservation.endTime,-->
<!--                status: mapBackendStatusToFrontend(reservation.status),-->
<!--                canCancel: reservation.canCancel,-->
<!--                canCheckIn: reservation.canCheckIn,-->
<!--                backendStatus: reservation.status, // 保存后端状态用于逻辑判断-->
<!--                seatStatus: reservation.seatStatus-->
<!--            };-->

<!--            if (isToday && isActive) {-->
<!--                currentBookings.push(bookingData);-->
<!--            } else {-->
<!--                historyBookings.push(bookingData);-->
<!--            }-->
<!--        });-->

<!--        return { currentBookings, historyBookings };-->
<!--    }-->

<!--    // 8. 时间计算函数-->
<!--    function calculateCheckInTimeRange(bookingStartTime, bookingEndTime) {-->
<!--        const now = new Date();-->
<!--        const startHour = parseInt(bookingStartTime.split(':')[0]);-->
<!--        const endHour = parseInt(bookingEndTime.split(':')[0]);-->

<!--        const bookingStart = new Date();-->
<!--        bookingStart.setHours(startHour, 0, 0, 0);-->

<!--        const bookingEnd = new Date();-->
<!--        bookingEnd.setHours(endHour, 0, 0, 0);-->

<!--        let checkInStart, checkInEnd;-->

<!--        if (now >= bookingStart && now <= bookingEnd) {-->
<!--            checkInStart = new Date(now);-->
<!--            checkInEnd = new Date(now.getTime() + 30 * 60 * 1000);-->
<!--        } else {-->
<!--            checkInStart = new Date(bookingStart.getTime() - 30 * 60 * 1000);-->
<!--            checkInEnd = new Date(bookingStart.getTime() + 30 * 60 * 1000);-->
<!--        }-->

<!--        return {-->
<!--            start: checkInStart,-->
<!--            end: checkInEnd-->
<!--        };-->
<!--    }-->

<!--    // 9. UI 更新函数-->
<!--    function updateCurrentBookingDisplay() {-->
<!--        const currentBookingsList = document.getElementById('current-bookings-list');-->
<!--        const noBookingMessage = document.getElementById('no-booking-message');-->

<!--        if (currentBookings.length > 0) {-->
<!--            currentBookingsList.innerHTML = '';-->
<!--            noBookingMessage.style.display = 'none';-->

<!--            currentBookings.forEach(booking => {-->
<!--                const bookingCard = document.createElement('div');-->
<!--                bookingCard.className = 'current-booking-card';-->
<!--                bookingCard.id = `booking-${booking.id}`;-->

<!--                // 根据状态确定按钮状态和显示文本-->
<!--                const { checkInBtnText, checkInBtnDisabled, leaveBtnText, leaveBtnDisabled, cancelBtnDisabled, timeInfo } = getBookingDisplayConfig(booking);-->

<!--                bookingCard.innerHTML = `-->
<!--                <div class="time-info ${timeInfo.class}" id="time-info-${booking.id}">-->
<!--                    ${timeInfo.text}-->
<!--                </div>-->
<!--                <div class="booking-info">-->
<!--                    <div class="info-item">-->
<!--                        <span class="info-label">预约区域</span>-->
<!--                        <span class="info-value">${booking.floorName}</span>-->
<!--                    </div>-->
<!--                    <div class="info-item">-->
<!--                        <span class="info-label">座位号</span>-->
<!--                        <span class="info-value">${booking.seatId}</span>-->
<!--                    </div>-->
<!--                    <div class="info-item">-->
<!--                        <span class="info-label">预约时间段</span>-->
<!--                        <span class="info-value">${booking.date} ${booking.startTime}-${booking.endTime}</span>-->
<!--                    </div>-->
<!--                    <div class="info-item">-->
<!--                        <span class="info-label">座位状态</span>-->
<!--                        <span class="info-value">-->
<!--                            <span class="status-badge ${booking.status}" id="current-status-${booking.id}">${getStatusText(booking.status)}</span>-->
<!--                        </span>-->
<!--                    </div>-->
<!--                </div>-->
<!--                <div class="booking-actions">-->
<!--                    <button class="btn btn-primary check-in-btn" data-id="${booking.id}" ${checkInBtnDisabled ? 'disabled' : ''}>${checkInBtnText}</button>-->
<!--                    <button class="btn btn-secondary temporary-leave-btn" data-id="${booking.id}" ${leaveBtnDisabled ? 'disabled' : ''}>${leaveBtnText}</button>-->
<!--                    <button class="btn btn-danger cancel-booking-btn" data-id="${booking.id}" ${cancelBtnDisabled ? 'disabled' : ''}>退座</button>-->
<!--                </div>-->
<!--            `;-->

<!--                currentBookingsList.appendChild(bookingCard);-->
<!--            });-->

<!--            // 重新绑定事件监听器-->
<!--            bindCurrentBookingEvents();-->

<!--        } else {-->
<!--            currentBookingsList.innerHTML = '';-->
<!--            noBookingMessage.style.display = 'block';-->
<!--        }-->
<!--    }-->

<!--    // 获取预约显示配置-->
<!--    function getBookingDisplayConfig(booking) {-->
<!--        console.log("状态" + booking.seatStatus);-->
<!--        const config = {-->
<!--            checkInBtnText: '落座',-->
<!--            checkInBtnDisabled: false,-->
<!--            leaveBtnText: '暂离',-->
<!--            leaveBtnDisabled: true,-->
<!--            cancelBtnDisabled: false,-->
<!--            timeInfo: { class: '', text: '' }-->
<!--        };-->

<!--        // switch(booking.backendStatus) {-->
<!--        //     case 'pending_fulfillment':-->
<!--        //         config.checkInBtnText = '落座';-->
<!--        //         config.checkInBtnDisabled = false;-->
<!--        //         config.leaveBtnText = '暂离';-->
<!--        //         config.leaveBtnDisabled = true;-->
<!--        //         config.timeInfo = {-->
<!--        //             class: 'warning',-->
<!--        //             text: '请在规定时间内完成落座，否则将自动释放座位'-->
<!--        //         };-->
<!--        //         break;-->
<!--        //-->
<!--        //     case 'fulfilled':-->
<!--        //         config.checkInBtnText = '已落座';-->
<!--        //         config.checkInBtnDisabled = true;-->
<!--        //         config.leaveBtnText = '暂离';-->
<!--        //         config.leaveBtnDisabled = false;-->
<!--        //         config.timeInfo = {-->
<!--        //             class: '',-->
<!--        //             text: '座位使用中，可点击"暂离"暂时离开座位'-->
<!--        //         };-->
<!--        //         break;-->
<!--        // }-->
<!--        //-->
<!--        // return config;-->
<!--         switch(booking.backendStatus) {-->
<!--            case 'pending_fulfillment':-->
<!--                config.checkInBtnText = '落座';-->
<!--                config.checkInBtnDisabled = false;-->
<!--                config.leaveBtnText = '暂离';-->
<!--                config.leaveBtnDisabled = true;-->
<!--                config.timeInfo = {-->
<!--                    class: 'warning',-->
<!--                    text: '请在规定时间内完成落座，否则将自动释放座位'-->
<!--                };-->
<!--                break;-->

<!--            case 'fulfilled':-->
<!--                config.checkInBtnText = '已落座';-->
<!--                config.checkInBtnDisabled = true;-->

<!--                // 根据seatStatus判断按钮文本-->
<!--                if (booking.seatStatus === 'AWAY') {-->
<!--                    config.leaveBtnText = '返回';-->
<!--                    config.timeInfo = {-->
<!--                        class: 'warning',-->
<!--                        text: '请在90分钟内返回并落座，否则将自动释放座位并记违约'-->
<!--                    };-->
<!--                } else {-->
<!--                    config.leaveBtnText = '暂离';-->
<!--                    config.timeInfo = {-->
<!--                        class: '',-->
<!--                        text: '座位使用中，可点击"暂离"暂时离开座位'-->
<!--                    };-->
<!--                }-->
<!--                config.leaveBtnDisabled = false;-->
<!--                break;-->
<!--        }-->

<!--        return config;-->
<!--    }-->

<!--    // 辅助函数：获取状态文本-->
<!--    function getStatusText(status) {-->
<!--        const statusMap = {-->
<!--            'pending': '待履约',-->
<!--            'fulfilled': '已履约',-->
<!--            'temporary-leave': '暂离中',-->
<!--            'expired': '已过期',-->
<!--            'completed': '已履约',-->
<!--            'canceled': '已取消',-->
<!--            'breach': '违约'-->
<!--        };-->
<!--        return statusMap[status] || '待履约';-->
<!--    }-->

<!--    function updateHistoryBookingsDisplay() {-->
<!--        historyBookingList.innerHTML = '';-->

<!--        if (historyBookings.length === 0) {-->
<!--            const row = document.createElement('tr');-->
<!--            row.innerHTML = `-->
<!--            <td colspan="4" style="text-align: center; color: #7f8c8d; padding: 40px;">-->
<!--                暂无历史预约记录-->
<!--            </td>-->
<!--        `;-->
<!--            historyBookingList.appendChild(row);-->
<!--            return;-->
<!--        }-->

<!--        historyBookings.forEach(booking => {-->
<!--            const row = document.createElement('tr');-->
<!--            row.className = 'booking-row';-->

<!--            let statusClass = '';-->
<!--            let statusText = '';-->

<!--            switch(booking.status) {-->
<!--                case 'completed':-->
<!--                    statusClass = 'completed';-->
<!--                    statusText = '已履约';-->
<!--                    break;-->
<!--                case 'canceled':-->
<!--                    statusClass = 'canceled';-->
<!--                    statusText = '已取消';-->
<!--                    break;-->
<!--                case 'breach':-->
<!--                    statusClass = 'breach';-->
<!--                    statusText = '违约';-->
<!--                    break;-->
<!--                case 'fulfilled':-->
<!--                    statusClass = 'fulfilled';-->
<!--                    statusText = '已履约';-->
<!--                    break;-->
<!--                case 'temporary-leave':-->
<!--                    statusClass = 'temporary-leave';-->
<!--                    statusText = '暂离中';-->
<!--                    break;-->
<!--                default:-->
<!--                    statusClass = 'pending';-->
<!--                    statusText = '待履约';-->
<!--            }-->

<!--            row.innerHTML = `-->
<!--            <td>${booking.floorName}</td>-->
<!--            <td>${booking.seatId}</td>-->
<!--            <td>${booking.date} ${booking.startTime}-${booking.endTime}</td>-->
<!--            <td><span class="status-badge ${statusClass}">${statusText}</span></td>-->
<!--        `;-->
<!--            historyBookingList.appendChild(row);-->
<!--        });-->
<!--    }-->

<!--    // 10. 业务逻辑函数-->
<!--    async function loadReservationData() {-->
<!--        try {-->
<!--            const reservations = await fetchUserReservations();-->
<!--            const processed = processReservations(reservations);-->

<!--            currentBookings = processed.currentBookings;-->
<!--            historyBookings = processed.historyBookings;-->

<!--            updateCurrentBookingDisplay();-->
<!--            updateHistoryBookingsDisplay();-->

<!--        } catch (error) {-->
<!--            console.error('加载预约数据失败:', error);-->
<!--            alert('加载预约数据失败');-->
<!--        }-->
<!--    }-->

<!--    function setMaxDateForFilter() {-->
<!--        const today = new Date();-->
<!--        const todayStr = formatDate(today);-->
<!--        dateFilter.max = todayStr;-->
<!--    }-->

<!--    function filterHistoryBookings() {-->
<!--        const status = statusFilter.value;-->
<!--        const date = dateFilter.value;-->

<!--        const rows = historyBookingList.querySelectorAll('.booking-row');-->

<!--        rows.forEach(row => {-->
<!--            let showRow = true;-->

<!--            if (status !== 'all') {-->
<!--                const rowStatus = row.querySelector('.status-badge').textContent;-->
<!--                const statusMap = {-->
<!--                    'completed': '已履约',-->
<!--                    'pending': '待履约',-->
<!--                    'canceled': '已取消',-->
<!--                    'breach': '违约'-->
<!--                };-->

<!--                if (statusMap[status] !== rowStatus) {-->
<!--                    showRow = false;-->
<!--                }-->
<!--            }-->

<!--            if (date) {-->
<!--                const rowDate = row.cells[2].textContent.split(' ')[0];-->
<!--                if (rowDate !== date) {-->
<!--                    showRow = false;-->
<!--                }-->
<!--            }-->

<!--            row.style.display = showRow ? '' : 'none';-->
<!--        });-->
<!--    }-->

<!--    // 11. 新增暂离和返回功能-->
<!--    async function temporaryLeave(e) {-->
<!--        const bookingId = e.target.dataset.id;-->
<!--        const booking = currentBookings.find(b => b.id == bookingId);-->
<!--        if (!booking) return;-->

<!--        try {-->
<!--            const username = sessionStorage.getItem('currentUser');-->
<!--            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/away`, {-->
<!--                method: 'POST',-->
<!--                headers: {-->
<!--                    'username': username,-->
<!--                    'Content-Type': 'application/json'-->
<!--                }-->
<!--            });-->

<!--            if (!response.ok) {-->
<!--                const errorText = await response.text();-->
<!--                throw new Error(errorText);-->
<!--            }-->

<!--            // 关键修改：暂离成功后立即更新按钮状态，无需等待重新加载数据-->
<!--            e.target.textContent = '返回';-->
<!--            // 更新提示信息-->
<!--            const timeInfoElement = document.getElementById(`time-info-${bookingId}`);-->
<!--            if (timeInfoElement) {-->
<!--                timeInfoElement.className = 'time-info warning';-->
<!--                timeInfoElement.textContent = '请在90分钟内返回并落座，否则将自动释放座位并记违约';-->
<!--            }-->

<!--            alert('暂离成功！请在90分钟内返回');-->

<!--        } catch (error) {-->
<!--            console.error('暂离失败:', error);-->
<!--            alert('暂离失败: ' + error.message);-->
<!--        }-->
<!--    }-->

<!--    async function returnFromLeave(e) {-->
<!--        const bookingId = e.target.dataset.id;-->
<!--        const booking = currentBookings.find(b => b.id == bookingId);-->
<!--        if (!booking) return;-->

<!--        try {-->
<!--            const username = sessionStorage.getItem('currentUser');-->
<!--            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/return`, {-->
<!--                method: 'POST',-->
<!--                headers: {-->
<!--                    'username': username,-->
<!--                    'Content-Type': 'application/json'-->
<!--                }-->
<!--            });-->

<!--            if (!response.ok) {-->
<!--                const errorText = await response.text();-->
<!--                throw new Error(errorText);-->
<!--            }-->

<!--            // 关键修改：返回成功后立即更新按钮状态，无需等待重新加载数据-->
<!--            e.target.textContent = '暂离';-->
<!--            // 更新提示信息-->
<!--            const timeInfoElement = document.getElementById(`time-info-${bookingId}`);-->
<!--            if (timeInfoElement) {-->
<!--                timeInfoElement.className = 'time-info';-->
<!--                timeInfoElement.textContent = '座位使用中，可点击"暂离"暂时离开座位';-->
<!--            }-->

<!--            alert('返回成功！');-->

<!--        } catch (error) {-->
<!--            console.error('返回失败:', error);-->
<!--            alert('返回失败: ' + error.message);-->
<!--        }-->
<!--    }-->

<!--    // 12. 事件处理函数-->
<!--    async function handleCheckIn(e) {-->
<!--        const bookingId = e.target.dataset.id;-->
<!--        const booking = currentBookings.find(b => b.id == bookingId);-->
<!--        if (!booking) return;-->

<!--        try {-->
<!--            const username = sessionStorage.getItem('currentUser');-->
<!--            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/checkin`, {-->
<!--                method: 'POST',-->
<!--                headers: {-->
<!--                    'username': username,-->
<!--                    'Content-Type': 'application/json'-->
<!--                }-->
<!--            });-->

<!--            if (!response.ok) {-->
<!--                const errorText = await response.text();-->
<!--                throw new Error(errorText);-->
<!--            }-->

<!--            alert('签到成功！');-->
<!--            await loadReservationData();-->

<!--        } catch (error) {-->
<!--            console.error('签到失败:', error);-->
<!--            alert('签到失败: ' + error.message);-->
<!--        }-->
<!--    }-->

<!--    async function handleTemporaryLeave(e) {-->
<!--        const bookingId = e.target.dataset.id;-->
<!--        const booking = currentBookings.find(b => b.id == bookingId);-->
<!--        if (!booking) return;-->

<!--        // 根据按钮文本判断当前操作-->
<!--        if (e.target.textContent === '暂离') {-->
<!--            // 执行暂离操作-->
<!--            await temporaryLeave(e);-->
<!--        } else if (e.target.textContent === '返回') {-->
<!--            // 执行返回操作-->
<!--            await returnFromLeave(e);-->
<!--        }-->
<!--    }-->

<!--    async function handleCancelBooking(e) {-->
<!--        const bookingId = e.target.dataset.id;-->
<!--        const booking = currentBookings.find(b => b.id == bookingId);-->
<!--        if (!booking) return;-->

<!--        if (!confirm('确定要退座吗？')) return;-->

<!--        try {-->
<!--            const username = sessionStorage.getItem('currentUser');-->
<!--            const response = await fetch(`${BASE_URL}/seat/reservation/${bookingId}/cancel`, {-->
<!--                method: 'POST',-->
<!--                headers: {-->
<!--                    'username': username,-->
<!--                    'Content-Type': 'application/json'-->
<!--                }-->
<!--            });-->

<!--            if (!response.ok) {-->
<!--                const errorText = await response.text();-->
<!--                throw new Error(errorText);-->
<!--            }-->

<!--            alert('退座成功！');-->
<!--            await loadReservationData();-->

<!--        } catch (error) {-->
<!--            console.error('退座失败:', error);-->
<!--            alert('退座失败: ' + error.message);-->
<!--        }-->
<!--    }-->

<!--    // 13. 初始化函数-->
<!--    function initializeElements() {-->
<!--        statusFilter = document.getElementById('status-filter');-->
<!--        dateFilter = document.getElementById('date-filter');-->
<!--        historyBookingList = document.getElementById('history-booking-list');-->
<!--    }-->

<!--    function bindEventListeners() {-->
<!--        // 为筛选控件添加事件监听-->
<!--        if (statusFilter) {-->
<!--            statusFilter.addEventListener('change', filterHistoryBookings);-->
<!--        }-->
<!--        if (dateFilter) {-->
<!--            dateFilter.addEventListener('change', filterHistoryBookings);-->
<!--        }-->
<!--    }-->

<!--    // 绑定当前预约卡片的事件-->
<!--    function bindCurrentBookingEvents() {-->
<!--        const currentBookingsList = document.getElementById('current-bookings-list');-->
<!--        if (currentBookingsList) {-->
<!--            currentBookingsList.addEventListener('click', function(e) {-->
<!--                if (e.target.classList.contains('check-in-btn')) {-->
<!--                    handleCheckIn(e);-->
<!--                } else if (e.target.classList.contains('temporary-leave-btn')) {-->
<!--                    handleTemporaryLeave(e);-->
<!--                } else if (e.target.classList.contains('cancel-booking-btn')) {-->
<!--                    handleCancelBooking(e);-->
<!--                }-->
<!--            });-->
<!--        }-->
<!--    }-->

<!--    async function initialize() {-->
<!--        const user = sessionStorage.getItem('currentUser');-->
<!--        if (!user) {-->
<!--            alert('请先登录');-->
<!--            location.href = 'login.html';-->
<!--            return;-->
<!--        }-->

<!--        await loadUserInfo(user);-->
<!--        initializeElements();-->
<!--        bindEventListeners();-->
<!--        setMaxDateForFilter();-->
<!--        await loadReservationData();-->
<!--    }-->

<!--    // 14. 程序入口-->
<!--    document.addEventListener('DOMContentLoaded', initialize);-->
<!--</script>-->
<!--</body>-->
<!--</html>-->